using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using UnityEngine;

public class Net : MonoBehaviour
{
    private static Net instance;
    public static Net Instance => instance;

    private Socket socketClient;

    private Queue<string> sendMessageQueue = new Queue<string>();
    private Queue<string> receiveMessageQueue = new Queue<string>();

    
    private Thread sendThread;
    private Thread receiveThread;

    private byte[] receiveBytes = new byte[1024];

    private int receiveNum;

    private bool isConnected = false;

    private void Awake()
    {
        instance = this;
        DontDestroyOnLoad(this.gameObject);
    }

    private void Update()
    {
        if(receiveMessageQueue.Count > 0)
        {
            print(receiveMessageQueue.Dequeue());
        }
    }
    public void Connect(string ip,int port)
    {
        if(isConnected) 
            return;
        if (socketClient == null)
            socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        IPEndPoint ipPoint = new IPEndPoint(IPAddress.Parse(ip), port);
        socketClient.Connect(ipPoint);

        isConnected = true;

        ThreadPool.QueueUserWorkItem(SendMessage);
        ThreadPool.QueueUserWorkItem(ReceiveMessage);
    }
    public void Send(string message)
    {
        sendMessageQueue.Enqueue(message);
    }
    public void SendMessage(object obj)
    {
        while(isConnected)
        {
            if(sendMessageQueue.Count > 0)
            {
                socketClient.Send(Encoding.UTF8.GetBytes(sendMessageQueue.Dequeue()));
            }
        }
    }
    private void ReceiveMessage(object obj)
    {
        while (isConnected)
        {
            if (socketClient.Available > 0)
            {
                receiveNum = socketClient.Receive(receiveBytes);
                receiveMessageQueue.Enqueue(Encoding.UTF8.GetString(receiveBytes, 0, receiveNum));
            }
        }
    }
    public void Close()
    {
        if(socketClient != null)
        {
            socketClient.Shutdown(SocketShutdown.Both);
            socketClient.Close();

            isConnected = false;
            
        }
    }
    private void OnDestroy()
    {
        Close();
    }
}
